package face.pay.open.material.service.impl;

import com.face.pay.IPayConfigServer;
import com.face.pay.SecurityConfig;
import com.face.pay.WxApiConfig;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayRequest;
import com.github.wxpay.sdk.WXPayUtil;
import face.pay.dao.MchApplymentInfoDao;
import face.pay.dao.OemConfigInfoDao;
import face.pay.dao.OemInfoDao;
import face.pay.entity.MchApplymentInfo;
import face.pay.open.material.service.IMchApplyMentQueryService;
import face.pay.open.server.CertficatesServer;
import face.pay.open.util.request.ApiRequestParam;
import face.pay.open.util.request.ErrorCode;
import face.pay.open.validate.ApiParamValidate;
import face.pay.util.ResultMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Auther: zkj
 * @Date: 2019/8/31 15:53
 * @Description:
 */
@Service
@Slf4j
public class MchApplyMentQueryServiceImpl implements IMchApplyMentQueryService {

    private static final String domain = "api.mch.weixin.qq.com";

    @Autowired
    private ApiParamValidate apiParamValidate;

    @Autowired
    private OemConfigInfoDao oemConfigInfoDao;

    @Autowired
    private OemInfoDao oemInfoDao;

    @Autowired
    private IPayConfigServer wxApiConfigServer;


    @Autowired
    private CertficatesServer certficatesServer;

    @Autowired
    private MchApplymentInfoDao mchApplymentInfoDao;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage applyMentQuery(String json) {

        log.info("商户进件双胎查询：报文"+json);

        Integer code = ErrorCode.ERROR;

        String message  = "未知错误";

        Boolean flag= true;


        ApiRequestParam apiRequestParam  = apiParamValidate.parse(json);


        try{
            if(apiRequestParam!=null) {

                Integer oemId = apiRequestParam.getOemId();

                log.info("oemId:"+oemId);
                WxApiConfig config = wxApiConfigServer.getConfig(oemId);

                if(config==null){
                    code = ErrorCode.ERROR;
                    message ="平台配置信息不全";
                }else {
                    SecurityConfig securityConfig = config.getSecurityConfig();

                    Map<String, String> data = apiRequestParam.getData();


                    Boolean validate =  apiParamValidate.validate(data,apiRequestParam.getSign(),securityConfig);

                    if(validate){
                        Integer userId = Integer.parseInt(data.get("userId"));

                        Integer applyId = Integer.parseInt(data.get("applyId"));


                        String applyment_id = data.get("applyment_id");

                        MchApplymentInfo applymentInfo =  new MchApplymentInfo();

                        applymentInfo.setId(applyId);
                        applymentInfo.setOemId(oemId);

                        MchApplymentInfo mchApplymentInfo = this.mchApplymentInfoDao.getApplyMent(applymentInfo);

                        if(mchApplymentInfo!=null){
                            Map<String, String> map =  new HashMap<>();

                            map.put("version", "1.0");

                            map.put("applyment_id", mchApplymentInfo.getApplyment_id());
                            map.put("business_code", mchApplymentInfo.getBusiness_code());

                            map.put("mch_id",config.getMchID());
                            map.put("sign_type", "HMAC-SHA256");
                            String nonce_str = WXPayUtil.generateNonceStr();

                            map.put("nonce_str", nonce_str);
                            String xml = WXPayUtil.generateSignedXml(map, config.getKey(), WXPayConstants.SignType.HMACSHA256);

                            log.info("调用微信进件查询接口:" + xml);
                            WXPayRequest wxPayRequest = new WXPayRequest(config);

                            String urlSuffix = "/applyment/micro/getstate";

                            String result = wxPayRequest.requestOnce(domain, urlSuffix, UUID.randomUUID().toString(), xml, 8000, 6000, true);

                            log.info("微信进件查询接口返回结果:" + result);
                            Map<String, String> resultMap = WXPayUtil.xmlToMap(result);


                            Boolean isOk = WXPayUtil.isSuccess(resultMap);

                            if(isOk){

                                Map<String, String> resultData = new HashMap<>();

                                resultData.put("applyment_id", resultMap.get("applyment_id"));

                                resultData.put("applyment_state", resultMap.get("applyment_state"));

                                resultData.put("applyment_state_desc", resultMap.get("applyment_state_desc"));

                                resultData.put("sub_mch_id", resultMap.get("sub_mch_id"));

                                resultData.put("sign_url", resultMap.get("sign_url"));

                                resultData.put("audit_detail", resultMap.get("audit_detail"));

                                return   ResultMessage.createSuccess("请求成功",resultData);

                            }
                        }
                    }else {
                        code = ErrorCode.SING_ERROR;
                        message = ErrorCode.SING_ERROR_MESSAGE;

                    }


                }
            }

        }catch (Exception e){
            log.error("进件异常",e);
            code = ErrorCode.ERROR;
        }
        return ResultMessage.createFail(message).setErrorCode(code);
    }
}
